package cn.com.sinosoft.testxmltransform;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;


/**
 * xml相关的工具类
 * @author xiaoxiong
 *
 */
public class XmlHandler {

	/**
	 * javabean转换为xml文本
	 * @param bean	被转换的javabean
	 * @return	xml文本
	 */
	public static Document beanToXmlDocument(Object bean) {
		Document document = DocumentHelper.createDocument();
		document.add(beanToXmlElement(bean));
		return document;
	}
	
	/**
	 * javabean转换为xml节点元素
	 * @param bean	被转换的javabean
	 * @args	不被解析的属性
	 * @return	xml节点元素
	 */
	public static Element beanToXmlElement(Object bean, String ... args) {
		String rootname = bean.getClass().getSimpleName();	//	获得类名
		Element root = DocumentHelper.createElement(rootname);	//	创建根节点
		Field[] properties = bean.getClass().getDeclaredFields();	//	获得实体类的所有属性 
		for (int i = 0; i < properties.length; i++) {
			Boolean isContinue = true;
			String pname = properties[i].getName();
			for(String arg : args) {
				if(arg.equals(pname)) {
					isContinue = false;
					break;
				}
			}
			if(!isContinue) {
				continue;
			}
			Method meth = null;
			try {
				meth = bean.getClass().getMethod("get" + properties[i].getName().substring(0, 1).toUpperCase()   
				                + properties[i].getName().substring(1));
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} 
			String returnType = meth.getReturnType().getName();
			if(("java.lang.String").equals(returnType)) {
				try {
					root.addElement(properties[i].getName()).setText(meth.invoke(bean)==null?"":meth.invoke(bean).toString());
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
			} else if(("java.util.List").equals(returnType)) {	//	递归转换子实体
				Element child = DocumentHelper.createElement(pname);
				List<?> list = null;
				try {
					list = (List<?>) meth.invoke(bean);
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
				if(list != null) {
					for(int j=0; j<list.size(); j++) {
						child.add(beanToXmlElement(list.get(j), "serialVersionUID"));
					}
				}
				root.add(child);
			}
		}
		return root;
	}
	
	/**
	 * xml元素转换为java对象
	 * @param element	xml元素
	 * @param bean	java对象
	 * @return	赋值后的java对象
	 */
	@SuppressWarnings("unchecked")
	public static Object xmlElementToBean(Element element, Object bean) {
		List<Element> childs = element.elements();
		if(childs != null && childs.size() > 0) {
			for(Element child : childs) {
				String name = child.getName();	//	节点名称
				List<Element> cElements = child.elements();
				if(cElements != null && cElements.size() > 0) {	//	当前元素具有子元素，则递归对子属性进行数据的绑定
					Child c = bean.getClass().getAnnotation(Child.class);
					if(c != null) {
						Class<Object>[] clazzes = (Class<Object>[]) c.clazz();
						if(clazzes != null) {
							for(int i=0; i<clazzes.length; i++) {
								for(int j=0; j<cElements.size(); j++) {
									Element ce = (Element) child.elements().get(j);
									String ceName = ce.getName();
									if(ceName.equals(clazzes[i].getSimpleName())) {
										try {
											Method meth = bean.getClass().getMethod("add" + ceName, clazzes[i]);
											meth.invoke(bean, xmlElementToBean(ce, clazzes[i].newInstance()));
										} catch (InstantiationException e) {
											e.printStackTrace();
										} catch (IllegalAccessException e) {
											e.printStackTrace();
										} catch (NoSuchMethodException e) {
											continue;
										} catch (SecurityException e) {
											e.printStackTrace();
										} catch (IllegalArgumentException e) {
											e.printStackTrace();
										} catch (InvocationTargetException e) {
											e.printStackTrace();
										}
									}
								}
							}
						}
					}
				} else {	//	当前元素不具有子元素，则直接进行赋值
					String value = child.getTextTrim();	//	节点文本值
					Field field = null;
					try {
						field = bean.getClass().getDeclaredField(name);
						PropertyDescriptor pd = new PropertyDescriptor(field.getName(), bean.getClass());
						pd.getWriteMethod().invoke(bean, value);
					} catch (NoSuchFieldException e) {	//	绑定的对象中找不到匹配当前元素名称的属性，则跳出当前循环
						continue;
					} catch (SecurityException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						e.printStackTrace();
					} catch (IntrospectionException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return bean;
	}
	
	/**
	 * xml字符串转换成bean对象
	 * @param xmlStr xml字符串
	 * @param clazz 待转换的class
	 * @return 转换后的对象
	 */
	public static Object xmlStrToBean(String xmlStr, Class<?> clazz) {
		Object obj = null;
		try {
			Map<String, Object> map = xmlStrToMap(xmlStr);	// 将xml格式的数据转换成Map对象
			obj = mapToBean(map, clazz);	//	将map对象的数据转换成Bean对象
		} catch(Exception e) {
			e.printStackTrace();
		}
		return obj;
	}
	
	/**
	 * 将xml格式的字符串转换成Map对象
	 * @param xmlStr xml格式的字符串
	 * @return Map对象
	 * @throws Exception 异常
	 */
	public static Map<String, Object> xmlStrToMap(String xmlStr){
		if(xmlStr == null || "".equals(xmlStr)) {
			throw new NullPointerException("被转换的XML文本为空");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		Document doc = null;
		try {
			doc = DocumentHelper.parseText(xmlStr);	//将xml格式的字符串转换成Document对象
		} catch (DocumentException e) {
			e.printStackTrace();
		}	
		Element root = doc.getRootElement();	//获取根节点
		List<?> children = root.elements();	//获取根节点下的所有元素
		if(children != null && children.size() > 0) {	//循环所有子元素
			for(int i = 0; i < children.size(); i++) {
				Element child = (Element)children.get(i);
				map.put(child.getName(), child.getTextTrim());
			}
		}
		return map;
	}
	
	/**
	 * 将Map对象通过反射机制转换成Bean对象
	 * @param map 存放数据的map对象
	 * @param clazz 待转换的class
	 * @return 转换后的Bean对象
	 * @throws Exception 异常
	 */
	public static Object mapToBean(Map<String, Object> map, Class<?> clazz) throws Exception {
		Object obj = clazz.newInstance();
		if(map != null && map.size() > 0) {
			for(Map.Entry<String, Object> entry : map.entrySet()) {
				String propertyName = entry.getKey();
				Object value = entry.getValue();
				String setMethodName = "set"
						+ propertyName.substring(0, 1).toUpperCase()
						+ propertyName.substring(1);
				Field field = getClassField(clazz, propertyName);
				Class<?> fieldTypeClass = field.getType();
				value = convertValType(value, fieldTypeClass);
				clazz.getMethod(setMethodName, field.getType()).invoke(obj, value);
			}
		}
		return obj;
	}
	
	/**
	 * 将Object类型的值，转换成bean对象属性里对应的类型值
	 * @param value Object对象值
	 * @param fieldTypeClass 属性的类型
	 * @return 转换后的值
	 */
	private static Object convertValType(Object value, Class<?> fieldTypeClass) {
		Object retVal = null;
		if(Long.class.getName().equals(fieldTypeClass.getName())
				|| long.class.getName().equals(fieldTypeClass.getName())) {
			retVal = Long.parseLong(value.toString());
		} else if(Integer.class.getName().equals(fieldTypeClass.getName())
				|| int.class.getName().equals(fieldTypeClass.getName())) {
			retVal = Integer.parseInt(value.toString());
		} else if(Float.class.getName().equals(fieldTypeClass.getName())
				|| float.class.getName().equals(fieldTypeClass.getName())) {
			retVal = Float.parseFloat(value.toString());
		} else if(Double.class.getName().equals(fieldTypeClass.getName())
				|| double.class.getName().equals(fieldTypeClass.getName())) {
			retVal = Double.parseDouble(value.toString());
		} else {
			retVal = value;
		}
		return retVal;
	}

	/**
	 * 获取指定字段名称查找在class中的对应的Field对象(包括查找父类)
	 * @param clazz 指定的class
	 * @param fieldName 字段名称
	 * @return Field对象
	 */
	private static Field getClassField(Class<?> clazz, String fieldName) {
		if( Object.class.getName().equals(clazz.getName())) {
			return null;
		}
		Field []declaredFields = clazz.getDeclaredFields();
		for (Field field : declaredFields) {
			if (field.getName().equals(fieldName)) {
				return field;
			}
		}
		Class<?> superClass = clazz.getSuperclass();
		if(superClass != null) {	// 简单的递归一下
			return getClassField(superClass, fieldName);
		}
		return null;
	}  

}
